﻿using System.Collections.Generic;
using System.Web;
using PetaPoco;

namespace CNF.Common.Base.SimpleOrm.DataBaseProvidrer
{
    public class PerRequestDataBaseStoreage : IDataBaseStoreage<Database>
    {
        protected const string ItemContextKey = "PerRequestDataBaseStoreage";

        protected Database CreateNewDataBaseByKey(string key)
        {
            return new Database(key);
        }

        public Database GetCurentDataBaseByKey(string key)
        {
            if (HttpContext.Current != null)
            {
                if (!HttpContext.Current.Items.Contains(ItemContextKey))
                {
                    HttpContext.Current.Items.Add(ItemContextKey, new Dictionary<string, Database>());
                }

                Dictionary<string, Database> databases = HttpContext.Current.Items[ItemContextKey] as Dictionary<string, Database>;

                if (!databases.ContainsKey(key))
                {
                    databases.Add(key, CreateNewDataBaseByKey(key));
                }

                return databases[key];
            }
            else
            {
                Dictionary<string, Database> databases = new Dictionary<string, Database>();
                databases.Add(key, CreateNewDataBaseByKey(key));
                return databases[key];

            }
        }
    }
}
